package com.clickpaas.governmentcloud.monitor;

import com.clickpaas.governmentcloud.config.AutoLoadConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 项目启动初始化这个类
 */
@Slf4j
@Component
public class FileMonitor implements CommandLineRunner {

    @Resource
    private FileAnalysis fileAnalysis;

    @Override
    public void run(String... args) throws Exception {
        init(AutoLoadConfig.FILE_PATH);
    }

    private void init(String filePath){
        long millis = TimeUnit.SECONDS.toMillis(5);
        FileAlterationObserver observer = new FileAlterationObserver(
                filePath,
                FileFilterUtils.and(
                        FileFilterUtils.fileFileFilter(),
                        /**
                         * 过滤其他文件格式，只支持.csv
                         */
                        FileFilterUtils.suffixFileFilter(".csv")),
                null
        );
        observer.addListener(new MonitorDic(fileAnalysis));
        FileAlterationMonitor monitor = new FileAlterationMonitor(millis, observer);
        try {
            monitor.start();
        } catch (Exception e) {
            log.error("config Load failure：{}",e);
        }
    }
}
